import * as utils from '@/utils/index'
import WebView from '@/components/WebView/index.js'
import { handleDecode } from '@/utils/handleUrl'
import { navigateTo } from '@/utils/tools'
// 点击 广告图跳转
const list = {
  assignPage: '', // 指定页面
  sendCounpon: '', // 送优惠券
  openApp: '', // 打开app
  filmSource: '/subPages/filmDetail/filmDetail?filmId=', // 影片资料页
  goodsDetail: '/pages/goodDetail/index?mallCommodityId=', // 指定商品详情页
  planPage: '/chooseSet?planKey=', // 特定排期页面
  sellGoodDetail: '/snackDetail?cinemaGoodsId=', // 指定卖品详情页
  activityPage: '/activityDetail?activityId=', // 活动列表页指定活动
  songbei: '/songbei', // 送呗首页
  shoppingMall: '/pages/mall/mall', // 商城首页
  VIP: '/vipRights', // 会员VIP首页
  information: '', // 资讯列表页
  shoppingMallZone: '/zoneGoods?zoneId=', // 商城专区
  informationNew: '/infoDetail?informationId=' // 资讯详情
}
export default {
  data() {
    return {}
  },
  methods: {
    // 使用 scheme 跳转小程序
    navigateToMiniProgramScheme({ scheme, success, fail }) {
      let { params, message } = this.schemeToParams(scheme)
      if (params) {
        my.navigateToMiniProgram({ ...params, success, fail })
      } else {
        fail &&
          fail({
            error: -1,
            errorMessage: `无效的小程序 scheme ${scheme}: ${message}`
          })
      }
    },

    // 将 scheme 转换为 my.navigateToMiniProgram 的参数
    schemeToParams(scheme) {
      if (!scheme.startsWith('alipays:')) {
        return { message: '! 非 alipays: 开头' }
      }
      let params = {}
      let parseQuery = (str) => {
        return str
          .replace(/^.*?\?/, '')
          .split('&amp;')
          .map((s) => {
            let p = s.includes('=') ? s.indexOf('=') : s.length
            return [s.slice(0, p), s.slice(p + 1)].map(decodeURIComponent)
          })
      }
      for (let [k, v] of parseQuery(scheme)) {
        if (k == 'appId') {
          if (v.length != 16) {
            return { message: `! 非 16 位 appId '${v}'` }
          }
        } else if (k == 'page') {
          k = 'path'
        } else if (k == 'query') {
          let o = {}
          for (let [x, y] of parseQuery(v)) {
            o[x] = y
          }
          v = o
        } else {
          return { message: `! 不支持参数 '${k}' ` }
        }
        params[k] = v
      }
      return { params }
    },

    // // 调用示例
    // let scheme = 'alipays://platformapi/startapp?appId=2022061812345678&amp;page=%2Fpages%2Findex%2Findex&amp;query=foo%3Dbar';
    // navigateToMiniProgramScheme({
    //   scheme,
    //   fail: (error) => {
    //     console.error('navigateToMiniProgramScheme fail: ', JSON.stringify(error));
    //   },
    // });
    // operatorType 操作类型 1 点击 2 关闭 3 跳过
    handleJump(info, operatorType = '1') {
      // #ifdef MP-ALIPAY
      //支付宝广告条写死2024年2月1日13:42:32
      if (info.type == '2') {
        // this.navigateToMiniProgramScheme({
        //   scheme,
        //   success: () => {},
        //   fail: (error) => {
        //     console.error(
        //       'navigateToMiniProgramScheme fail: ',
        //       JSON.stringify(error)
        //     )
        //   }
        // })
        const targetUrl =
          'alipays://platformapi/startapp?appId=68687451&url=%2Fwww%2Fbc-join.html%3Foid%3D2024012215425900084767%26businessId%3D2024012215425900084767%26businessType%3D18%26source%3DTINYAPP'
        my.ap.openURL({
          url: targetUrl,
          fail: (res) => {
            my.showToast({
              content: '跳转失败'
            })
          }
        })
      } else {
        if (!my.canIUse('plugin') && !my.isIDE) {
          console.log('不可用', my.canIUse('plugin'), my.isIDE)
          my.ap && my.ap.updateAlipayClient && my.ap.updateAlipayClient() // 如果动态加载不可用则打开支付宝客户端升级界面
        } else {
          my.reLaunch({
            url: `plugin://groupPurchaseoucherPlugin/index?outItemId=${info.mallCommodityId}`
            // outItemId为外部商品id
          })
        }
      }
      // #endif
      // #ifndef MP-ALIPAY
      console.log('handleJump', info)
      //   window.canGo = '1'
      const item = info.jump
      const type = item.type
      //   this.handleUm(type)
      const data = {
        adId: info.adId,
        adType: info.adType,
        classification: info.classification || '0',
        operatorType: operatorType
      }
      console.log(info)
      info.adId && uni.$api.poster.upAdLog(data) // 埋点请求(接口)
      if (operatorType !== '1') {
        return
      }
      if (type === 'onlyPicture') {
        return
      } else if (type === 'jumpLink') {
        //#ifdef H5
        const url = this.handleDecode(item.value)
        const isRouterPush = this.handleRouterPush(url)
        if (isRouterPush) {
          return
        }
        if (url.includes('goout=1')) {
          window.location.href = url
          return
        }
        WebView.show(item.value, true, info.name || '')
        //#endif
        //#ifdef MP-WEIXIN
        console.log(item.value)
        navigateTo(`/pages/webview/webview`, {
          url: item.value,
          title: info.name
        })
        //#endif
      } else {
        console.log('type', type)
        const path = list[type]
        const value = item.value
        if (!path) {
          console.warn('广告跳转未找到对应配置路由')
        } else {
          const query = utils.obj2Param(item)
          const flag = path.includes('?') ? '&' : '?'
          const routerPath: any = `${path}${value}${flag}${query}`
          if (type === 'shoppingMall') {
            navigateTo(path, undefined, 'switchTab')
          } else {
            navigateTo(routerPath)
          }
        }
      }
      // #endif
    },
    handleDecode,
    handleRouterPush(url) {
      url = url.replace(/http(|s)\:\/\//, '')
      if (url.startsWith('/pages' || '/subPages')) {
        navigateTo(url.slice(1))
        return true
      } else {
        return
      }
    }
  }
}
